package com.ezgo.erc.master.utils;

import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * (工具)模块 TODO(线程池管理)
 * 
 * @author devintam
 * @date 2015年8月7日 下午4:49:31
 *
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ThreadPoolManager {
	private static Log log = LogFactory.getLog(ThreadPoolManager.class);

	private ThreadPoolManager() {
	}

	public static ThreadPoolManager newInstance() {
		return new ThreadPoolManager();
	}

	/** 线程池执行者 */
	private ThreadPoolExecutor taskPool = null;

	/** 任务队列 */
	private BlockingQueue taskQueue = null;

	private int corePoolSize = 3;
	private int maxPoolSize = 3;
	private int queueSize = 6;
	private long waitTime = 60;

	public final static String THREADPOOL_POOLSIZE_KEY = "corePoolSize";
	public final static String THREADPOOL_MAXSIZE_KEY = "maxPoolSize";
	public final static String THREADPOOL_QUEUESIZE_KEY = "queueSize";
	public final static String THREADPOOL_WAITTIME_KEY = "waitTime";

	public void init(Properties p) {
		if (p != null) {
			corePoolSize = Integer.parseInt(p
					.getProperty(THREADPOOL_POOLSIZE_KEY));
			maxPoolSize = Integer.parseInt(p
					.getProperty(THREADPOOL_MAXSIZE_KEY));
			queueSize = Integer.parseInt(p
					.getProperty(THREADPOOL_QUEUESIZE_KEY));
			waitTime = Long.parseLong(p.getProperty(THREADPOOL_WAITTIME_KEY));
		}
		taskQueue = new ArrayBlockingQueue(queueSize);

		taskPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, waitTime,
				TimeUnit.SECONDS, taskQueue,
				new ThreadPoolExecutor.CallerRunsPolicy());

		log.info("Initialize thread pool succeed. ThreadPool: corePoolSize = "
				+ corePoolSize + ", queueSize = " + queueSize
				+ ", maxPoolSize = " + maxPoolSize);
	}

	public void run(Runnable command) {
		this.taskPool.execute(command);
	}
}
